package advance.x000.acw_95;


import java.util.Scanner;


public class Main2 {

    public static int step;
    public static Scanner scanner;
    public static int[][] lamp;

    //递归实现排列型枚举
    public static void main(String[] args) {
        Main2 solution = new Main2();
        scanner = new Scanner(System.in);
        // 5X5 组数
        int n = scanner.nextInt();
        for (int k = 0; k < n; k++) {
            step = 0;
            solution.readLamp();
            solution.clac(0, 0);
        }
    }

    private void clac(int cur, int j) {
        if (cur == 5) {
            System.out.println(-1);
        }
        if (checkLight()) {
            System.out.println(step);
        }
        // 一层一层往下算,遇上0就往下j+1,尝试电灯，继续
        // 输入电灯的位置，上下左右的灯反置状态

        light(cur, j);
        for (int k = 0; k < 5; k++) {
            if (lamp[cur][k] == 0) {
                clac(cur + 1, k);
            }
        }
        clac(cur + 1, 0);
        // 恢复状态
        light(cur, j);
    }

    public void light(int i, int j) {
        lamp[i][j] = ~lamp[i][j];
        if (i - 1 >= 0) lamp[i - 1][j] = ~lamp[i - 1][j];
        if (j - 1 >= 0) lamp[i][j - 1] = ~lamp[i][j - 1];
        if (i + 1 < 5) lamp[i + 1][j] = ~lamp[i + 1][j];
        if (j + 1 < 5) lamp[i][j + 1] = ~lamp[i][j + 1];
    }

    private boolean checkLight() {
        int light = 1;
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                light &= lamp[i][j];
            }
        }
        return light == 1 ? true : false;
    }

    private void readLamp() {
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                lamp[i][j] = scanner.nextInt();
            }
        }
    }


}
